package com.sky.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.config.CombatClassConfig;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.IEmployeeService;
import com.sky.utils.JwtUtil;
import com.sky.vo.EmployeeLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private IEmployeeService iEmployeeService;
    @Autowired
    private CombatClassConfig combatClassConfig;

    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();
        LambdaQueryWrapper<Employee> lqw =new LambdaQueryWrapper<>();
        lqw.eq(employeeLoginDTO.getUsername()!=null&&!employeeLoginDTO.getUsername().trim().isEmpty(),
                Employee::getUsername,employeeLoginDTO.getUsername());
        //1、根据用户名查询数据库中的数据
        Employee employee = iEmployeeService.getOne(lqw);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        String password1 = employeeLoginDTO.getPassword();
        String s = DigestUtils.md5DigestAsHex(password1.getBytes());
        if (!s.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }


        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

        return Result.success(employeeLoginVO);
    }

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }

    @GetMapping("/page")
    public Result getList(EmployeePageQueryDTO pageQuery, Employee employee) {
        IPage<Employee> iPage =new Page<>(pageQuery.getPage(),pageQuery.getPageSize());
        LambdaQueryWrapper<Employee> lqw =new LambdaQueryWrapper<>();
        lqw.like(employee.getName()!=null&&!employee.getName().trim().isEmpty()
                ,Employee::getName,employee.getName());
        lqw.orderByDesc(Employee::getCreateTime);
        iEmployeeService.page(iPage,lqw);
        return Result.success(iPage);
    }

    @PostMapping
    public Result add(@RequestBody Employee employee){
        String  defaultPassword = combatClassConfig.getDefaultPassword();
        String s = DigestUtils.md5DigestAsHex(defaultPassword.getBytes());
        employee.setPassword(s);
        iEmployeeService.save(employee);
        return Result.success();
    }

    @PostMapping("/status/{value}")
    public Result updateStatus(@PathVariable Integer value , Long id){
        LambdaUpdateWrapper<Employee> luw =new LambdaUpdateWrapper<>();
        luw.eq(Employee::getId,id).set(Employee::getStatus,value);
        iEmployeeService.update(luw);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getOne(@PathVariable Long id){
        Employee byId = iEmployeeService.getById(id);
        return Result.success(byId);
    }

    @PutMapping
    public Result update(@RequestBody Employee employee){
        iEmployeeService.updateById(employee);
        return Result.success();
    }
}
